<?php
namespace App\Http\Controllers\Api;

use App\Helper\Utils\TimeUtil;
use App\V3\V3_1\Models\AdminModel;
use App\V3\V3_1\Models\CheckModel;
use App\V3\V3_1\Models\SellDriverModel;
use App\V3\V3_1\Models\SellGoodsDetail;
use App\V3\V3_1\Models\SellModel;
use App\V3\V3_1\Models\SellOtherChargesModel;
use App\V3\V3_1\Models\SellPayRecord;
use App\V3\V3_1\Models\StorageManageModel;
use App\V3\V3_1\Models\SupplierCustomerModel;
use App\Services\IncomeExpensesService;
use App\Services\OutInRepealService;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

/**
 * 销售
 * Class SellController
 * @package App\Http\Controllers\Api
 */
class SellController extends BaseController
{
    /**
     * 销售列表
     * change 在 2021/11/3 15:11 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'pageSize' =>'required|integer',//页面大小
            'currentPage' =>'required|integer',//当前页
            'repeal_status'=>'required|integer'//撤销状态：0-未撤销 1-已撤销
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        //查询
        if($this->getUserId()==$this->getMainUserId()){
            $model = SellModel::where(['main_id'=>$this->getMainUserId(),'repeal_status'=>$data['repeal_status']])
                ->where('delete_flag', 0)
                ->orderBy('id','desc')
                ->paginate($data['pageSize'],['*'], '',$data['currentPage'])
                ->toArray();
        }else{
            $model = SellModel::where(['main_id'=>$this->getMainUserId(),'repeal_status'=>$data['repeal_status'],'user_id'=>$this->getUserId()])
                ->where('delete_flag', 0)
                ->orderBy('id','desc')
                ->paginate($data['pageSize'],['*'], '',$data['currentPage'])
                ->toArray();
        }
        if($model['data']){
            foreach ($model['data'] as &$value){
                $value['username'] = AdminModel::where('id',$value['user_id'])->value('username');
                $value['goods_info'] = SellGoodsDetail::where('sell_id',$value['id'])->get();
                $value['driver'] =  SellDriverModel::where('sell_id',$value['id'])->first();
            }
        }
        return $this->success($model);
    }

    /**
     * 详情
     * change 在 2021/11/3 10:09 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function find(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' =>'required|integer',//销售单主键id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $model = SellModel::find($data['id']);
        if($model){
            $model['username'] = AdminModel::where('id',$model['user_id'])->value('username');
            $model['compony_name'] = SupplierCustomerModel::where(['name'=>$model['customer_name'],'main_id'=>$this->getMainUserId()])->value('compony_name');
            $model['goods_info'] = SellGoodsDetail::where('sell_id',$model['id'])->get();
            foreach ($model['goods_info'] as &$val){
                $val['in_storage_num'] = StorageManageModel::where(['materiel_name'=>$val['name'],'type_name'=>$val['type_name'],'main_id'=>$this->getMainUserId()])->value('in_storage_num');
            }
            $model['driver'] = SellDriverModel::where('sell_id',$model['id'])->first();
        }
        return $this->success($model);
    }

    /**
     * 添加销售单
     * change 在 2021/11/1 16:46 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function add(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'customer_name' =>'required|string',//客户姓名
            'goods_info' =>'required|string',//商品信息  json array
            'discount' =>'integer',//折扣 ：百分比
            'tax_rate' =>'integer',//税率 ：百分比
            'is_zero_suppression' =>'required|integer',//是否抹零：0-否 1-是
            'final_money' =>'string',//实际应收金额（即折扣或抹零后价格）
            'deliver_goods_type' =>'integer',//发货方式：1-自提 2-代发 3-送货
            'transport_type' =>'integer',//运输方式：1-空运 2-海运 3-铁路 4-公路
            'consignee' =>'string',//收货人
            'phone' =>'string',//联系电话
            'address' =>'string',//地址
            'remark' =>'string',//备注
            'out_order_no' =>'string',//外部单号
            'sell_date' =>'required|date',//销售时间
            'proof_image' =>'string',//凭证图片(多图逗号分隔)
            'real_money' =>'string',//实收金额（实际入账）
            'is_draft' =>'required|integer',//是否草稿：1-是 0-否
            'source' =>'integer'//订单来源:0-未知 1-安卓 2-ios 3-pc 4-微信小程序 5-抖音小程序
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        //开启事务
        DB::beginTransaction();
        try{
            //报溢报损主单
            $mainInfo = $data;
            unset($mainInfo['goods_info']);
            $mainInfo['main_id'] = $this->getMainUserId();
            $mainInfo['user_id'] = $this->getUserId();
            $mainInfo['created_at'] = time();
            $mainInfo['sell_date'] = strtotime($data['sell_date']);
            $mainInfo['order_no'] = 'S'. $this->getMainUserId().TimeUtil::getMillisecond();//订单号
            //创建销售主单信息
            $mainId = SellModel::insertGetId($mainInfo);
            //商品详细添加
            $goodsInfo = json_decode($data['goods_info'],true);
            $money = 0;//货款金额
            foreach ($goodsInfo as &$value){
                $value['main_id'] = $this->getMainUserId();
                $value['sell_date'] = strtotime(date('Y-m-d',strtotime($data['sell_date'])));
                $value['sell_id'] = $mainId;
                $value['created_at'] = time();
                $money+=($value['price']*$value['num']);
            }
            //非改价计算价格
            if(!$data['is_zero_suppression'] && $money){
                $finalMoney = 0;
                if(isset($data['discount']) && $data['discount']){//折扣
                    $finalMoney+= ($data['discount']*$money/100);
                }else{
                    $finalMoney = $money;
                }
                if(isset($data['tax_rate']) && $data['tax_rate']){//加税点
                    $finalMoney+= ($data['tax_rate']*$finalMoney/100);
                }

                SellModel::where('id',$mainId)->update(['final_money'=>$finalMoney,'money'=>$money]);
            }else{
                SellModel::where('id',$mainId)->update(['money'=>$money]);
            }
            SellGoodsDetail::insert($goodsInfo);
            //审核列表
            CheckModel::insert([
                'type'=>2,
                'all_id'=>$mainId,
                'main_id'=>$this->getMainUserId(),
                'user_id'=>$this->getUserId(),
                'order_no'=>$mainInfo['order_no'],
                'created_at'=>time(),
                'updated_at'=>time()

            ]);

            //实收全部结清更新支付状态为全部
//            if(isset($mainInfo['real_money']) && (string)$mainInfo['real_money']==(string)$finalMoney){
//                SellModel::where('id',$mainId)->update(['pay_status'=>2]);
//            }
            DB::commit();//提交事务
            return $this->success($mainId);
        }catch (Exception $e){
            DB::rollBack();//事务回滚
            //异常响应
            return $this->fail($e->getMessage(),'添加销售单');
        }
    }

    /**
     * 编辑销售单
     * change 在 2021/11/1 16:45 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function edit(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' =>'required|integer',//主键id
            'customer_name' =>'string',//客户姓名
            'goods_info' =>'string',//商品信息  json array
            'discount' =>'integer',//折扣 ：百分比
            'tax_rate' =>'integer',//税率 ：百分比
            'is_zero_suppression' =>'integer',//是否抹零：0-否 1-是
            'final_money' =>'string',//实际应收金额（即折扣或抹零后价格不含运费）
            'deliver_goods_type' =>'integer',//发货方式：1-自提 2-代发 3-送货
            'transport_type' =>'integer',//运输方式：1-空运 2-海运 3-铁路 4-公路
            'consignee' =>'string',//收货人
            'phone' =>'string',//联系电话
            'address' =>'string',//地址
            'remark' =>'string',//备注
            'out_order_no' =>'string',//外部单号
            'sell_date' =>'required|date',//销售时间
            'proof_image' =>'string',//凭证图片(多图逗号分隔)
            'real_money' =>'string',//实收金额（实际入账）
            'logistics_company' =>'string',//物流公司
            'logistics_order_no' =>'string',//物流单号
            //            'other_charges' =>'string',//其他费用（运费）不能修改
            'order_time' =>'string',//下单时间
            'deliver_time' =>'string',//发货时间
            'deliver_person' =>'string',//发货人
            'deliver_phone' =>'string',//发货人联系方式
            'deliver_addr' =>'string',//发货地址
            'source' =>'integer',//订单来源:0-未知 1-安卓 2-ios 3-pc 4-微信小程序 5-抖音小程序
            'driver' =>'string',//司机信息  json array
            'is_draft' =>'required|integer',//是否草稿：1-是 0-否
            'total_piece' =>'integer',//商品总件数
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        //开启事务
        DB::beginTransaction();
        try{
            //报溢报损主单
            $mainInfo = $data;
            if(isset($mainInfo['sell_date'])) $mainInfo['sell_date'] = strtotime($data['sell_date']);
            if(isset($mainInfo['order_time'])) $mainInfo['order_time'] = strtotime($data['order_time']);
            if(isset($mainInfo['deliver_time'])) $mainInfo['deliver_time'] = strtotime($data['deliver_time']);

            //商品详细添加
            if(isset($mainInfo['goods_info']) && !empty($mainInfo['goods_info'])){
                $goodsInfo = json_decode($data['goods_info'],true);
                $money = 0;//货款金额
                foreach ($goodsInfo as $value){//更新商品信息
                    $money+=($value['price']*$value['num']);
                    $goods = SellGoodsDetail::where(['sell_id'=>$data['id'],'name'=>$value['name'],'type_name'=>$value['type_name']])->first();
                    $value['sell_date'] = strtotime(date('Y-m-d',strtotime($data['sell_date'])));
                    //更新
                    if($goods){
                        SellGoodsDetail::where(['sell_id'=>$data['id'],'name'=>$value['name'],'type_name'=>$value['type_name']])->update($value);
                    }else{//添加
                        $value['main_id'] = $this->getMainUserId();
                        $value['sell_id'] = $data['id'];
                        $value['created_at'] = time();
                        SellGoodsDetail::insert($value);
                    }

                }
                //非改价计算价格
                if(!$data['is_zero_suppression'] && $money){
                    $finalMoney = 0;
                    if(isset($data['discount']) && $data['discount']){//折扣
                        $finalMoney+= ($data['discount']*$money/100);
                    }else{
                        $finalMoney = $money;
                    }

                    if(isset($data['tax_rate']) && $data['tax_rate']){//加税点
                        $finalMoney+= ($data['tax_rate']*$finalMoney/100);
                    }

                    $mainInfo['final_money'] = $finalMoney;
                    $mainInfo['money'] = $money;
                }else{
                    $mainInfo['money'] = $money;
                }
                unset($mainInfo['goods_info']);
            }
            //实收全部结清更新支付状态为全部
//            if(isset($mainInfo['real_money']) && (string)$mainInfo['real_money']==(string)$finalMoney){
//                $mainInfo['pay_status'] =2;
//            }
            //司机更新添加
            if(isset($mainInfo['driver']) && !empty($mainInfo['driver'])){
                $driver = SellDriverModel::where('sell_id',$data['id'])->first();
                if($driver){
                    SellDriverModel::where('sell_id',$data['id'])->update(json_decode($mainInfo['driver'],true));
                }else{
                    $newDriver = json_decode($mainInfo['driver'],true);
                    $newDriver['sell_id'] = $data['id'];
                    $newDriver['main_id'] = $this->getMainUserId();
                    SellDriverModel::insert($newDriver);
                }
                unset($mainInfo['driver']);
            }
            //更新销售单
            SellModel::where('id',$data['id'])->update($mainInfo);
            DB::commit();//提交事务
            return $this->success();
        }catch (Exception $e){
            DB::rollBack();//事务回滚
            //异常响应
            return $this->fail($e->getMessage(),'添加销售单');
        }
    }

    /**
     * 删除销售订单
     * change 在 2021/11/2 15:51 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function del(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id'=>'required|integer',//销售单主键
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        SellModel::where('id', $data['id'])->update([
            'delete_flag' => 1
        ]);
        return $this->success();
    }
    /**
     * 收款
     * change 在 2021/11/1 16:47 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMoney(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'sell_id'=>'required|integer',//销售单主键
            'money'=>'required|string',//收款金额
            'collection_time'=>'required|date',//收款时间
            'collection_account'=>'required|string',//收款账号
            'status'=>'required|integer',//收款状态：1-全部 2-部分
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        //开启事务
        DB::beginTransaction();
        try{
            $model = SellModel::where('id',$data['sell_id'])->first();//销售单信息
            $inMomey = SellPayRecord::where('sell_id',$data['sell_id'])->sum('money');//已收款金额
            //全部收款
            if($data['status']==1){
                $model->pay_status = 2;
                $model->real_money = $model->final_money+$model->other_charges;
                $model->save();
                //支付完成更新商品支付状态
                SellGoodsDetail::where('sell_id',$data['sell_id'])->update(['pay_status'=>1]);
                $money = ($model['final_money']+$model['other_charges'])-$inMomey;
            }else{//部分收款
                //收款超额检测
                if(($inMomey+$data['money'])>($model['final_money']+$model['other_charges'])){
                    return $this->fail('','超出剩余应付金额');
                }
                if(($inMomey+$data['money'])<($model['final_money']+$model['other_charges'])){
                    $model->real_money = $inMomey+$data['money'];
                    $model->pay_status = 1;
                }
                if(($inMomey+$data['money'])==($model['final_money']+$model['other_charges'])){
                    $model->pay_status = 2;
                    $model->real_money = $model->final_money+$model->other_charges;
                    //支付完成更新商品支付状态
                    SellGoodsDetail::where('sell_id',$data['sell_id'])->update(['pay_status'=>1]);
                }
                $model->save();
                $money = $data['money'];
            }
            //收款记录
            if($data['money']){
                $data['collection_time'] = strtotime($data['collection_time']);
                $data['created_at'] = time();
                $data['main_id'] = $this->getMainUserId();
                unset($data['status']);
                SellPayRecord::insert($data);
            }
            //账单记录
            IncomeExpensesService::tally(0,$model['order_no'],$money,$this->getMainUserId(), $model['sell_date']);
            DB::commit();//提交事务
            return $this->success();
        }catch (\Exception $e){
            DB::rollBack();//事务回滚
            //异常响应
            return $this->fail($e->getMessage(),'销售单收款');
        }
    }

    /**
     * 撤销
     * change 在 2021/11/2 09:39 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function repeal(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id'=>'required|integer',//销售单主键
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $res = OutInRepealService::repeal($data['id'],1);
        if($res==0){
            return $this->fail('','商品被删除，无法撤销');
        }
        if($res==1){
            return $this->success();
        }
    }

    /**
     * 重新下单
     * change 在 2021/11/2 09:40 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addAgain(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id'=>'required|integer',//销售单主键
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        //开启事务
        DB::beginTransaction();
        try{
            //销售单新增
            $sell = SellModel::find($data['id'])->toArray();
            unset($sell['id']);
            unset($sell['updated_at']);
            $sell['user_id'] = $this->getUserId();
            $sell['repeal_status'] = 0;
            $sell['real_money'] = 0;
            $sell['out_status'] = 0;
            $sell['pay_status'] = 0;
            $sell['order_no'] = 'S'. $this->getMainUserId().TimeUtil::getMillisecond();//订单号
            $sell['created_at'] =time();
            $sell['sell_date'] = strtotime($sell['sell_date']);
            $sell['deliver_time'] = strtotime($sell['deliver_time']);
            $sell['order_time'] = strtotime($sell['order_time']);
            $mainId = SellModel::insertGetId($sell);
            //商品详细
            $sellGoods = SellGoodsDetail::select('materiel_type_id','name','type_name','price','num','image','warehouse','warehouse_id','main_id','materiel_no')->where('sell_id',$data['id'])->get()->toArray();
            if($sellGoods){
                foreach ($sellGoods as &$val){
                    $val['sell_id'] = $mainId;
                    $val['created_at'] =  time();
                }
                SellGoodsDetail::insert($sellGoods);
            }
            //司机
            $sellDriver = SellDriverModel::select('plate_number','name','phone','logistics_company','remark','plate_image','id_card_image','driving_licence','main_id')->where('sell_id',$data['id'])->first();
            if($sellDriver){
                $sellDriver = json_decode(json_encode($sellDriver),true);
                $sellDriver['sell_id'] = $mainId;
                $sellDriver['created_at'] = time();
                SellDriverModel::insert($sellDriver);
            }
            //其他费用
            $sellOtherCharges = SellOtherChargesModel::select('money','other_type_name','other_remark','main_id')->where('sell_id',$data['id'])->get()->toArray();
            if($sellOtherCharges){
                foreach ($sellOtherCharges as &$value){
                    $value['sell_id'] = $mainId;
                    $value['created_at'] =  time();
                }
                SellOtherChargesModel::insert($sellOtherCharges);
            }
            DB::commit();//提交事务
            return $this->success($mainId);
        }catch (Exception $e){
            DB::rollBack();//事务回滚
            //异常响应
            return $this->fail($e->getMessage(),'销售单收款');
        }
    }
    /**
     * 绑定司机(添加编辑)
     * change 在 2021/11/2 09:40 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function bindDriver(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'sell_id' =>'required|integer',//销售单主键id
            'plate_number' =>'required|string',//车牌
            'name' =>'required|string',//司机姓名
            'phone' =>'required|string',//提货司机电话
            'logistics_company' =>'string',//物流公司
            'remark' =>'string',//备注
            'plate_image' =>'string',//车牌照片
            'id_card_image' =>'string',//身份证照片
            'driving_licence' =>'string',//驾驶证照片
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $data['main_id'] = $this->getMainUserId();
        $data['created_at'] = time();
        $model = SellDriverModel::where('sell_id',$data['sell_id'])->first();
        if($model){
            unset($data['created_at']);
            SellDriverModel::where('sell_id',$data['sell_id'])->update($data);
        }else{
            SellDriverModel::insert($data);
        }
        return $this->success();
    }
    /**
     * 查看司机
     * change 在 2021/11/2 09:40 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function findDriver(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'sell_id' =>'required|integer',//销售单主键id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $model = SellDriverModel::where('sell_id',$data['sell_id'])->first();
        return $this->success($model);
    }

    /**
     * 其他费用添加
     * change 在 2021/11/2 14:41 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function otherCharges(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'sell_id' =>'required|integer',//销售单主键id
            'money' =>'required|string',//其他费用
            'other_type_name' =>'required|string',//其他费用类型名称
            'other_remark' =>'string',//备注
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $data['main_id'] = $this->getMainUserId();
        $data['created_at'] = time();
        //开启事务
        DB::beginTransaction();
        try{
            SellOtherChargesModel::insert($data);
            $model = SellModel::where('id',$data['sell_id'])->first();
            $model->other_charges = $model->other_charges+$data['money'];
            $model->save();
            DB::commit();//提交事务
            return $this->success();
        }catch (Exception $e){
            DB::rollBack();//事务回滚
            //异常响应
            return $this->fail($e->getMessage(),'添加其他费用');
        }
    }
    /**
     * 其他费用列表
     * change 在 2021/11/2 14:41 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function otherChargesList(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'sell_id' =>'required|integer',//销售单主键id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $model = SellOtherChargesModel::where('sell_id',$data['sell_id'])->get();
        return $this->success($model);
    }
    /**
     * 其他费用编辑
     * change 在 2021/11/2 14:41 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function otherChargesEdit(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' =>'required|integer',//其他费用主键id
            'money' =>'required|string',//其他费用
            'other_type_name' =>'string',//其他费用类型名称
            'other_remark' =>'string',//备注
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        //开启事务
        DB::beginTransaction();
        try{
            $beforeModel = SellOtherChargesModel::where('id',$data['id'])->first();
            SellOtherChargesModel::where('id',$data['id'])->update($data);
            $beforeMoney = $beforeModel['money'];
            $final = $data['money']-$beforeMoney;
            $model = SellModel::where('id',$beforeModel['sell_id'])->first();
            $model->other_charges = $model->other_charges+$final;
            $model->save();
            DB::commit();//提交事务
            return $this->success();
        }catch (Exception $e){
            DB::rollBack();//事务回滚
            //异常响应
            return $this->fail($e->getMessage(),'添加其他费用');
        }
    }

    /**
     * 出库
     * change 在 2021/11/11 10:28 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function out(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' => 'required|integer',//销售单主键id
            'status' => 'required|integer',//出入库状态：0-部分 1-全部
            'goods_info' => 'string',//商品信息  array
            'in_storage_time'=>'required|date',//出库时间
            'remark' => 'string',//备注
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        if($data['status']==0){//部分
            $res = OutInRepealService::outIn(1,$data['id'],1,$data['goods_info'],$data);//出库处理
            if($res==1){
                return $this->fail('','数量不符无法入库');
            }
            if(is_array($res)){
                return $this->fail('',$res['msg']);
            }
        }else {//全部
            $res = OutInRepealService::outIn(1,$data['id'],2,'',$data);//出库处理
            if(is_array($res)){
                return $this->fail('',$res['msg']);
            }
        }
        DB::commit();//提交事务
        return $this->success();
    }
}
